<template>
  <CommonLayout 
    pageTitle="公告管理"
    sidebarTitle="公告筛选"
    :showSidebar="true"
    :loading="loading"
    :isEmpty="announcements.length === 0"
    emptyText="暂无公告数据"
  >
    <!-- 侧边栏筛选内容 -->
    <template #sidebar>
      <div class="filter-group">
        <label class="filter-label">公告状态</label>
        <select v-model="filterStatus" class="filter-select" @change="fetchAnnouncements">
          <option value="-1">全部状态</option>
          <option value="0">草稿</option>
          <option value="1">已发布</option>
          <option value="2">已撤回</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label class="filter-label">时间范围</label>
        <div class="date-range">
          <input type="date" v-model="startDate" class="date-input" @change="fetchAnnouncements">
          <span class="date-separator">至</span>
          <input type="date" v-model="endDate" class="date-input" @change="fetchAnnouncements">
        </div>
      </div>
      
      <div class="filter-group">
        <label class="filter-label">关键字搜索</label>
        <div class="search-input-group">
          <input 
            type="text" 
            v-model="keyword" 
            class="search-input" 
            placeholder="输入标题或内容关键词"
            @input="debounceFetchAnnouncements"
          >
          <button class="search-btn" @click="fetchAnnouncements">搜索</button>
        </div>
      </div>
      
      <button class="reset-btn" @click="resetFilters">重置筛选条件</button>
    </template>
    
    <!-- 操作按钮 -->
    <template #actions>
      <button class="primary-btn" @click="createAnnouncement">发布新公告</button>
    </template>
    
    <!-- 主内容区 -->
    <template #content>
      <div class="announcement-table-container">
        <table class="announcement-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>标题</th>
              <th>状态</th>
              <th>是否置顶</th>
              <th>发布时间</th>
              <th>过期时间</th>
              <th>查看次数</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="announcement in announcements" :key="announcement.announcement_id">
              <td>{{ announcement.announcement_id }}</td>
              <td class="title-cell" @click="viewDetail(announcement.announcement_id)">{{ announcement.title }}</td>
              <td>
                <span :class="getStatusClass(announcement.status)">
                  {{ getStatusText(announcement.status) }}
                </span>
              </td>
              <td>{{ announcement.is_top ? '是' : '否' }}</td>
              <td>{{ formatDate(announcement.publish_time) }}</td>
              <td>{{ formatDate(announcement.expire_time) || '永久有效' }}</td>
              <td>{{ announcement.view_count }}</td>
              <td class="action-buttons">
                <button 
                  class="edit-btn" 
                  @click.stop="editAnnouncement(announcement.announcement_id)"
                  :disabled="announcement.status === 2"
                >
                  编辑
                </button>
                <button 
                  class="publish-btn" 
                  @click.stop="publishAnnouncement(announcement.announcement_id)"
                  v-if="announcement.status === 0"
                >
                  发布
                </button>
                <button 
                  class="recall-btn" 
                  @click.stop="recallAnnouncement(announcement.announcement_id)"
                  v-if="announcement.status === 1"
                >
                  撤回
                </button>
                <button 
                  class="delete-btn" 
                  @click.stop="deleteAnnouncement(announcement.announcement_id)"
                  :disabled="announcement.status === 1"
                >
                  删除
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 分页控件 -->
      <div v-if="pagination" class="pagination-controls">
        <button @click="changePage(1)" :disabled="pagination.currentPage === 1">首页</button>
        <button @click="changePage(pagination.currentPage - 1)" :disabled="pagination.currentPage === 1">上一页</button>
        <span v-for="pageNum in pageRange" :key="pageNum" :class="{ 'active': pageNum === pagination.currentPage }" @click="changePage(pageNum)">{{ pageNum }}</span>
        <button @click="changePage(pagination.currentPage + 1)" :disabled="pagination.currentPage === pagination.totalPages">下一页</button>
        <button @click="changePage(pagination.totalPages)" :disabled="pagination.currentPage === pagination.totalPages">末页</button>
        <span class="page-info">共 {{ pagination.totalPages }} 页 / {{ pagination.totalItems }} 条</span>
      </div>
    </template>
  </CommonLayout>
  
  <!-- 公告详情弹窗 -->
  <div v-if="showDetail" class="modal-overlay" @click="closeDetail">
    <div class="modal-content" @click.stop>
      <button class="close-btn" @click="closeDetail">×</button>
      <h2 class="detail-title">{{ currentAnnouncement?.title }}</h2>
      <div class="detail-meta">
        <span>发布时间: {{ formatDate(currentAnnouncement?.publish_time) }}</span>
        <span v-if="currentAnnouncement?.expire_time">过期时间: {{ formatDate(currentAnnouncement?.expire_time) }}</span>
      </div>
      <div class="detail-content" v-html="currentAnnouncement?.content"></div>
    </div>
  </div>
  
  <!-- 编辑/创建公告弹窗 -->
  <div v-if="showEditor" class="modal-overlay" @click="closeEditor">
    <div class="modal-content editor-modal" @click.stop>
      <button class="close-btn" @click="closeEditor">×</button>
      <h2 class="editor-title">{{ editingAnnouncement ? '编辑公告' : '创建公告' }}</h2>
      
      <form class="announcement-form" @submit.prevent="submitAnnouncement">
        <div class="form-group">
          <label class="form-label">公告标题 <span class="required">*</span></label>
          <input 
            type="text" 
            v-model="formData.title" 
            class="form-input" 
            placeholder="请输入公告标题"
            required
          >
        </div>
        
        <div class="form-group">
          <label class="form-label">公告内容 <span class="required">*</span></label>
          <textarea 
            v-model="formData.content" 
            class="form-textarea" 
            placeholder="请输入公告内容"
            rows="10"
            required
          ></textarea>
        </div>
        
        <div class="form-group">
          <label class="form-label">是否置顶</label>
          <input 
            type="checkbox" 
            v-model="formData.is_top" 
            class="form-checkbox"
          >
        </div>
        
        <div class="form-group">
          <label class="form-label">过期时间</label>
          <input 
            type="datetime-local" 
            v-model="formData.expire_time" 
            class="form-input"
          >
        </div>
        
        <div class="form-group" v-if="!editingAnnouncement">
          <label class="form-label">操作选项</label>
          <div class="radio-group">
            <label class="radio-label">
              <input 
                type="radio" 
                value="publish" 
                v-model="formAction"
                checked
              >
              直接发布
            </label>
            <label class="radio-label">
              <input 
                type="radio" 
                value="draft" 
                v-model="formAction"
              >
              保存为草稿
            </label>
          </div>
        </div>
        
        <div class="form-actions">
          <button type="button" class="cancel-btn" @click="closeEditor">取消</button>
          <button type="submit" class="submit-btn">{{ formAction === 'publish' ? '发布公告' : '保存草稿' }}</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import CommonLayout from '../components/CommonLayout.vue';
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import moment from 'moment';

// 响应式变量
const announcements = ref<Array<{
  announcement_id: number;
  title: string;
  content: string;
  author_id: number;
  is_top: number;
  status: number;
  view_count: number;
  publish_time: string;
  expire_time: string | null;
  created_at: string;
  updated_at: string;
}>>([]);
const loading = ref(true);
const API_BASE = import.meta.env.VITE_API_BASE_URL || 'http://localhost:5000';
const currentPage = ref(1);
const pageSize = ref(10);
const pagination = ref<{
  currentPage: number;
  pageSize: number;
  totalItems: number;
  totalPages: number;
} | null>(null);

// 筛选条件
const filterStatus = ref('-1'); // -1: 全部, 0: 草稿, 1: 已发布, 2: 已撤回
const startDate = ref('');
const endDate = ref('');
const keyword = ref('');

// 弹窗状态
const showDetail = ref(false);
const showEditor = ref(false);
const editingAnnouncement = ref<number | null>(null);
const currentAnnouncement = ref<{
  announcement_id: number;
  title: string;
  content: string;
  author_id: number;
  is_top: number;
  status: number;
  view_count: number;
  publish_time: string;
  expire_time: string | null;
  created_at: string;
  updated_at: string;
} | null>(null);

// 表单数据
const formData = ref<{
  title: string;
  content: string;
  is_top: number;
  expire_time: string | null;
}> ({
  title: '',
  content: '',
  is_top: 0,
  expire_time: null
});

const formAction = ref<'publish' | 'draft'>('publish');

/**
 * 获取公告列表
 */
const fetchAnnouncements = async () => {
  try {
    loading.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始请求获取公告列表: 页码=${currentPage.value}, 每页数量=${pageSize.value}`);
    
    const params: any = {
      page: currentPage.value,
      pageSize: pageSize.value
    };
    
    // 添加筛选条件
    if (filterStatus.value !== '-1') {
      params.status = filterStatus.value;
    }
    
    if (startDate.value) {
      params.startDate = startDate.value;
    }
    
    if (endDate.value) {
      params.endDate = endDate.value;
    }
    
    if (keyword.value) {
      params.keyword = keyword.value;
    }
    
    const apiUrl = `${API_BASE}/api/announcements/admin/list`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求URL: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios.get(apiUrl, { params, headers });
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 公告列表请求成功，状态码: ${response.status}`);
    announcements.value = response.data.data?.announcements || [];
    pagination.value = response.data.data?.pagination || null;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 公告列表获取成功: ${announcements.value.length} 条公告, 总条数: ${pagination.value?.totalItems || 0}`);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 获取公告列表失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`获取公告数据失败: ${err?.response?.data?.message || err.message}`);
  } finally {
    loading.value = false;
  }
};

/**
 * 防抖处理搜索
 */
const debounceFetchAnnouncements = (() => {
  let timer: any = null;
  return () => {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fetchAnnouncements();
    }, 500);
  };
})();

/**
 * 重置筛选条件
 */
const resetFilters = () => {
  filterStatus.value = '-1';
  startDate.value = '';
  endDate.value = '';
  keyword.value = '';
  fetchAnnouncements();
};

/**
 * 查看公告详情
 * @param announcementId 公告ID
 */
const viewDetail = async (announcementId: number) => {
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始请求查看公告详情: announcementId=${announcementId}`);
    
    const apiUrl = `${API_BASE}/api/announcements/${announcementId}`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求URL: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios.get(apiUrl, { headers });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 公告详情请求成功，状态码: ${response.status}`);
    
    currentAnnouncement.value = response.data.data || null;
    showDetail.value = true;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [AdminAnnouncements] 公告详情数据:`, currentAnnouncement.value);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 公告详情获取成功，标题: ${currentAnnouncement.value?.title}`);
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 获取公告详情失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`获取公告详情失败: ${err?.response?.data?.message || err.message}`);
  }
};

/**
 * 关闭公告详情
 */
const closeDetail = () => {
  showDetail.value = false;
  currentAnnouncement.value = null;
};

/**
 * 创建新公告
 */
const createAnnouncement = () => {
  editingAnnouncement.value = null;
  formData.value = {
    title: '',
    content: '',
    is_top: 0,
    expire_time: null
  };
  formAction.value = 'publish';
  showEditor.value = true;
};

/**
 * 编辑公告
 * @param announcementId 公告ID
 */
const editAnnouncement = async (announcementId: number) => {
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始请求编辑公告: announcementId=${announcementId}`);
    
    const apiUrl = `${API_BASE}/api/announcements/${announcementId}`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求URL: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios.get(apiUrl, { headers });
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 获取编辑公告数据成功，状态码: ${response.status}`);
    
    const announcement = response.data.data || null;
    if (announcement) {
      formData.value = {
        title: announcement.title,
        content: announcement.content,
        is_top: announcement.is_top,
        expire_time: announcement.expire_time ? moment(announcement.expire_time).format('YYYY-MM-DDTHH:mm') : null
      };
      editingAnnouncement.value = announcementId;
      showEditor.value = true;
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 编辑公告表单已加载，标题: ${announcement.title}`);
    }
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 获取编辑公告数据失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`获取公告编辑数据失败: ${err?.response?.data?.message || err.message}`);
  }
};

/**
 * 关闭编辑器
 */
const closeEditor = () => {
  showEditor.value = false;
  editingAnnouncement.value = null;
};

/**
 * 提交公告
 */
const submitAnnouncement = async () => {
  try {
    const isCreate = !editingAnnouncement.value;
    const apiUrl = isCreate 
      ? `${API_BASE}/api/announcements/admin` 
      : `${API_BASE}/api/announcements/admin/${editingAnnouncement.value}`;
    
    const method = isCreate ? 'post' : 'put';
    
    // 处理过期时间
    const expireTime = formData.value.expire_time 
      ? new Date(formData.value.expire_time).toISOString() 
      : null;
    
    const data = {
      title: formData.value.title,
      content: formData.value.content,
      is_top: formData.value.is_top,
      expire_time: expireTime,
      status: formAction.value === 'publish' ? 1 : 0
    };
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始${isCreate ? '创建' : '更新'}公告: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios[method](apiUrl, data, { headers });
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] ${isCreate ? '创建' : '更新'}公告成功，状态码: ${response.status}`);
    
    alert(`${isCreate ? '创建' : '更新'}公告${formAction.value === 'publish' ? '发布' : '保存草稿'}成功`);
    closeEditor();
    fetchAnnouncements();
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] ${!editingAnnouncement.value ? '创建' : '更新'}公告失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`${!editingAnnouncement.value ? '创建' : '更新'}公告失败: ${err?.response?.data?.message || err.message}`);
  }
};


/**
 * 发布公告
 * @param announcementId 公告ID
 */
const publishAnnouncement = async (announcementId: number) => {
  try {
    if (!confirm('确定要发布此公告吗？')) return;
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始发布公告: announcementId=${announcementId}`);
    
    const apiUrl = `${API_BASE}/api/announcements/admin/${announcementId}/publish`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求URL: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios.post(apiUrl, {}, { headers });
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 发布公告成功，状态码: ${response.status}`);
    
    alert('公告发布成功');
    fetchAnnouncements();
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 发布公告失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`发布公告失败: ${err?.response?.data?.message || err.message}`);
  }
};

/**
 * 撤回公告
 * @param announcementId 公告ID
 */
const recallAnnouncement = async (announcementId: number) => {
  try {
    if (!confirm('确定要撤回此公告吗？')) return;
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始撤回公告: announcementId=${announcementId}`);
    
    const apiUrl = `${API_BASE}/api/announcements/admin/${announcementId}/recall`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求URL: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios.post(apiUrl, {}, { headers });
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 撤回公告成功，状态码: ${response.status}`);
    
    alert('公告撤回成功');
    fetchAnnouncements();
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 撤回公告失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`撤回公告失败: ${err?.response?.data?.message || err.message}`);
  }
};

/**
 * 删除公告
 * @param announcementId 公告ID
 */
const deleteAnnouncement = async (announcementId: number) => {
  try {
    if (!confirm('确定要删除此公告吗？')) return;
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 开始删除公告: announcementId=${announcementId}`);
    
    const apiUrl = `${API_BASE}/api/announcements/admin/${announcementId}`;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求URL: ${apiUrl}`);
    
    // 获取token并设置请求头
    const token = localStorage.getItem('token');
    const headers = token ? { Authorization: `Bearer ${token}` } : {};
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 请求头:`, headers);
    
    const response = await axios.delete(apiUrl, { headers });
    
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [AdminAnnouncements] 删除公告成功，状态码: ${response.status}`);
    
    alert('公告删除成功');
    fetchAnnouncements();
  } catch (error) {
    const err = error as any;
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 删除公告失败: ${err.message}`);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 错误详情:`, err);
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [AdminAnnouncements] 响应数据:`, err?.response?.data);
    alert(`删除公告失败: ${err?.response?.data?.message || err.message}`);
  }
};

/**
 * 切换页码
 * @param pageNum 目标页码
 */
const changePage = (pageNum: number) => {
  if (pageNum < 1 || (pagination.value && pageNum > pagination.value.totalPages)) {
    return;
  }
  
  currentPage.value = pageNum;
  fetchAnnouncements();
};

/**
 * 生成页码范围
 */
const pageRange = computed(() => {
  if (!pagination.value) return [];
  const { currentPage, totalPages } = pagination.value;
  const range = [];
  const showPages = 5; // 显示的页码数量

  // 计算起始页码
  let startPage = Math.max(1, currentPage - Math.floor(showPages / 2));
  // 调整结束页码
  let endPage = startPage + showPages - 1;
  if (endPage > totalPages) {
    endPage = totalPages;
    startPage = Math.max(1, endPage - showPages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 格式化日期
 * @param dateStr 日期字符串
 * @returns 格式化后的日期
 */
const formatDate = (dateStr: string | null | undefined): string => {
  if (!dateStr) return '';
  return moment(dateStr).format('YYYY-MM-DD HH:mm:ss');
};

/**
 * 获取状态文本
 * @param status 状态码
 * @returns 状态文本
 */
const getStatusText = (status: number): string => {
  switch (status) {
    case 0: return '草稿';
    case 1: return '已发布';
    case 2: return '已撤回';
    default: return '未知状态';
  }
};

/**
 * 获取状态样式类名
 * @param status 状态码
 * @returns 样式类名
 */
const getStatusClass = (status: number): string => {
  switch (status) {
    case 0: return 'status-draft';
    case 1: return 'status-published';
    case 2: return 'status-recalled';
    default: return 'status-unknown';
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchAnnouncements();
});
</script>

<style scoped>
/* 表格样式 */
.announcement-table-container {
  overflow-x: auto;
  margin-bottom: 24px;
}

.announcement-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.announcement-table th, 
.announcement-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
}

.announcement-table th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #1e293b;
}

.title-cell {
  cursor: pointer;
  color: #2563eb;
  text-decoration: underline;
}

/* 状态标签样式 */
.status-draft {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #fef3c7;
  color: #92400e;
  font-size: 12px;
  font-weight: 500;
}

.status-published {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #d1fae5;
  color: #065f46;
  font-size: 12px;
  font-weight: 500;
}

.status-recalled {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #fee2e2;
  color: #b91c1c;
  font-size: 12px;
  font-weight: 500;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-btn, .publish-btn, .recall-btn, .delete-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.2s;
}

.edit-btn {
  background-color: #e0f2fe;
  color: #0369a1;
}

.edit-btn:hover:not(:disabled) {
  background-color: #bae6fd;
}

.edit-btn:disabled {
  background-color: #e2e8f0;
  color: #94a3b8;
  cursor: not-allowed;
}

.publish-btn {
  background-color: #dcfce7;
  color: #16a34a;
}

.publish-btn:hover {
  background-color: #bbf7d0;
}

.recall-btn {
  background-color: #fecdd3;
  color: #e11d48;
}

.recall-btn:hover {
  background-color: #fda4af;
}

.delete-btn {
  background-color: #fee2e2;
  color: #b91c1c;
}

.delete-btn:hover:not(:disabled) {
  background-color: #fecaca;
}

.delete-btn:disabled {
  background-color: #e2e8f0;
  color: #94a3b8;
  cursor: not-allowed;
}

/* 筛选样式 */
.filter-group {
  margin-bottom: 24px;
}

.filter-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #1e293b;
}

.filter-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background-color: #fff;
  font-size: 14px;
}

.date-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.date-separator {
  color: #64748b;
}

.search-input-group {
  display: flex;
  gap: 8px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.search-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background-color: #2563eb;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.search-btn:hover {
  background-color: #1d4ed8;
}

.reset-btn {
  width: 100%;
  padding: 8px 16px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background-color: #fff;
  color: #64748b;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.reset-btn:hover {
  background-color: #f8fafc;
  color: #1e293b;
}

/* 按钮样式 */
.primary-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  background-color: #2563eb;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.primary-btn:hover {
  background-color: #1d4ed8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  max-width: 600px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
  padding: 24px;
  position: relative;
}

.editor-modal {
  max-width: 800px;
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #64748b;
}

.detail-title {
  margin-top: 0;
  margin-bottom: 16px;
  color: #1e293b;
  font-size: 20px;
  font-weight: 600;
}

.detail-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  color: #64748b;
  font-size: 14px;
}

.detail-content {
  line-height: 1.6;
  color: #1e293b;
}

.editor-title {
  margin-top: 0;
  margin-bottom: 24px;
  color: #1e293b;
  font-size: 20px;
  font-weight: 600;
}

/* 表单样式 */
.announcement-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-weight: 500;
  color: #1e293b;
}

.required {
  color: #ef4444;
}

.form-input, .form-textarea {
  padding: 10px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.form-textarea {
  resize: vertical;
}

.form-checkbox {
  width: 16px;
  height: 16px;
}

.radio-group {
  display: flex;
  gap: 16px;
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

.cancel-btn, .submit-btn {
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.cancel-btn {
  border: 1px solid #e2e8f0;
  background-color: #fff;
  color: #64748b;
}

.cancel-btn:hover {
  background-color: #f8fafc;
}

.submit-btn {
  border: none;
  background-color: #2563eb;
  color: #fff;
}

.submit-btn:hover {
  background-color: #1d4ed8;
}

/* 分页样式 */
.pagination-controls {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin-top: 24px;
}

.pagination-controls button {
  padding: 6px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  background-color: #fff;
  color: #64748b;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.pagination-controls button:hover:not(:disabled) {
  border-color: #2563eb;
  color: #2563eb;
}

.pagination-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.pagination-controls span {
  padding: 6px 12px;
  cursor: pointer;
}

.pagination-controls span.active {
  color: #2563eb;
  font-weight: 600;
}

.page-info {
  color: #64748b;
  font-size: 14px;
  cursor: default;
}
</style>